package com.typhoon.spring_boot_demo1.manager;

import com.typhoon.spring_boot_demo1.dto.SearchResultDto;
import com.typhoon.spring_boot_demo1.request.Operator;
import com.typhoon.spring_boot_demo1.service.ISearch;
import com.typhoon.spring_boot_demo1.service.impl.SearchThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 查询管理器
 *
 */
@Service
public class SearchManager {

    @Autowired
    private List<ISearch> iSearchList;

    ExecutorService executorService = Executors.newFixedThreadPool(10);

    public List<SearchResultDto> search(String key, Operator operator) {
        List<SearchResultDto> list  = new ArrayList<>();
        if(null == iSearchList || iSearchList.isEmpty()) {
            return list;
        }
        List<Future<List<SearchResultDto>>> futureList = new ArrayList<>(iSearchList.size());
        iSearchList.forEach(iSearch -> {
             futureList.add(this.executorService.submit(new SearchThread(key,operator,iSearch)));
        });

       futureList.forEach(future -> {
           try {
               List<SearchResultDto>results = future.get();
               if(null != results && !results.isEmpty()) {
                   list.addAll(results);
               }
           } catch (Exception e) {
               e.printStackTrace();
           }
       });
        return list;
    }
}
